#!/usr/bin/env python
#
#       Database.py
#       
#       Copyright 2009 Robin Hayes <bonzairob@hotmail.co.uk>
#       Copyright 2009 Ben Davis <its.hip@gmail.com>
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.

import Options

import sys
import threading
import time
import urllib

from Clients import Clients
from Maps import Map
from Players import Players

clients = Clients()
map = Map()
players = Players()

class Database:
    def __init__(self, port, notes, username=None):
        self.port = port
        self.username = username
        self.notes = notes
        self.firstrun = True
        self.toreturn = ""
            
    def register(self):
        parameters = {'port': self.port, 'map': Options.MAPFILE, 'notes': self.notes}
        if self.username: 
            parameters['username'] = self.username
        if len(clients) > 0:
            parameters['users'] = ""
            for client in clients:
                parameters['users'] += client.player.name + ";"
        urlparams = urllib.urlencode(parameters)
        self.toreturn = ""
        try:
            urlf = urllib.urlopen("http://pandrgames.co.uk/dbmanip/register.php", urlparams) # - this crashes on mac
            #because it's called in a thread, stupid snow leopard. See AutoRegister's init
            
            if self.firstrun:
                print "Registered with P&R server."
                self.firstrun = False
            return urlf.read()
        except IOError:
            print "Unable to register with P&R server :("
            return

    
    def unregister(self):
        urlparams = urllib.urlencode({'notes': "Delete this. Unused."})
        urlf = urllib.urlopen("http://pandrgames.co.uk/dbmanip/register.php", urlparams)
        return urlf.read()
        
class AutoRegister(threading.Thread):
    def __init__(self, database):
        database.register()
        #If urllib is called outside of the thread, no crash on mac.
        threading.Thread.__init__(self)
        self.database = database
        self.stop = False
        
    def run(self):
        i = 0
        while not self.stop:
            i += 1
            # Sleep for one tenth of a second
            time.sleep(0.1)
            # If a minute has passed
            if i == 600:
                # Re-register with the server
                if self.database.register():
                    i = 0
                else:
                    # Wait three seconds and try again
                    i = 570
    
    def join(self):
        self.stop = True
        threading.Thread.join(self)